package com.wendy.utils;

import com.wendy.authentication.UserDetail;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author zhuwending
 */
@UtilityClass
public class SecurityUtil {

    /**
     * 获取Authentication
     *
     * @return Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户信息
     *
     * @param authentication Authentication
     * @return UserDetail
     */
    public UserDetail getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetail) {
            return (UserDetail) principal;
        }
        return null;
    }

    public UserDetail getUser() {
        Authentication authentication = getAuthentication();
        if (null == authentication) {
            return null;
        }
        return getUser(authentication);
    }

    public List<String> getRoles() {
        Authentication authentication = getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> roleIds = new ArrayList<>();
        authorities.forEach(granted -> roleIds.add(granted.getAuthority()));
        return roleIds;
    }
}
